package com.zyh.assessments.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.assessments.domain.Assessments;
import com.zyh.assessments.mapper.AssessmentsMapper;
import com.zyh.assessments.service.AssessmentsService;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.exam.domain.ExamPaper;
import com.zyh.exam.mapper.ExamPaperMapper;
import com.zyh.record.domain.ExamRecord;
import com.zyh.record.mapper.ExamRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author ZYH
 * @version 1.0
 * @date 2025-02-23
 */
@Service
public class AssessmentsServiceImpl extends ServiceImpl<AssessmentsMapper, Assessments> implements AssessmentsService {

    public static final Logger logger = Logger.getLogger(AssessmentsServiceImpl.class.getName());

    @Autowired
    private ExamRecordMapper examMapper;

    @Autowired
    private ExamPaperMapper examPaperMapper;

    /**
     * 获取历史消息
     * @return
     */
    @Override
    public AjaxResult getHistoryList() {
        try {
            // 初始化线程安全的Map
            Map<String, Object> resultMap = new HashMap<>();

            // 查询考试记录列表
            List<ExamRecord> examRecordList = examMapper.selectList(
                    new LambdaQueryWrapper<ExamRecord>()
                            .eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                            .eq(ExamRecord::getStatus, "1")       // 只查询已完成的测评
                            .in(ExamRecord::getDelFlag, "0", "2") // 同时查0（当前有效）和2（历史版本）
                            .orderByDesc(ExamRecord::getCreateTime)
            );
            if (examRecordList == null || examRecordList.isEmpty()) {
                // 如果考试记录为空，直接返回空结果
                resultMap.put("examPaperList", Collections.emptyList());
                resultMap.put("examRecordList", Collections.emptyList());
                return AjaxResult.success(resultMap);
            }
            // 提取试卷ID列表
            Set<Long> paperIds = examRecordList.stream()
                    .map(ExamRecord::getPaperId)
                    .collect(Collectors.toSet());

            // 根据paperIds查询有效试卷（del_flag=0）
            List<ExamPaper> examPaperList = examPaperMapper.selectList(
                    new LambdaQueryWrapper<ExamPaper>()
                            .in(ExamPaper::getId, paperIds)
                            .eq(ExamPaper::getDelFlag, "0") // 只查有效试卷
            );

            // 过滤掉关联试卷不存在的记录
            examRecordList = examRecordList.stream()
                    .filter(record -> examPaperList.stream()
                            .anyMatch(paper -> paper.getId().equals(record.getPaperId())))
                    .collect(Collectors.toList());
            // 将结果放入Map中
            resultMap.put("examPaperList", examPaperList);
            resultMap.put("examRecordList", examRecordList);

            return AjaxResult.success(resultMap);
        } catch (Exception e) {
            return AjaxResult.error("获取历史记录失败：" + e.getMessage());
        }
    }
}
